package com.dzx.design.behavioral.interpreter;

import java.util.Stack;

/**
 * @author dzx
 * @ClassName:
 * @Description:
 * @date 2019年08月14日 14:02:37
 */
public class GeelyExpressionParser {
    private Stack<Interpreter> stack = new Stack<Interpreter>();


    public int parse(String str) {
        String[] strItemArray = str.split(" ");
        for (String symbol : strItemArray) {
            //如果不是操作符，直接入栈
            if (!OperatorUtil.isOperator(symbol)) {
                Interpreter numberExpression = new NumberInterpreter(symbol);
                stack.push(numberExpression);
                System.out.println(String.format("入栈：%d", numberExpression.interpret()));
            } else {//如果是运算符号
                //取出栈顶的两个元素
                Interpreter firstExpression = stack.pop();
                Interpreter secondExpression = stack.pop();
                System.out.println(String.format("出栈：%d 和 %d", firstExpression.interpret(), secondExpression.interpret()));
                Interpreter operator = OperatorUtil.getExpressionObject(firstExpression, secondExpression, symbol);
                System.out.println(String.format("应用运算符：%s", operator.toString()));
                int result= operator.interpret();
                //将运算结果入栈
                NumberInterpreter resultExpression = new NumberInterpreter(result);
                stack.push(resultExpression);
                System.out.println(String.format("阶段结果入栈：%d", resultExpression.interpret()));

            }
            //如果是操作符
        }
        Interpreter pop = stack.pop();
        return pop.interpret();
    }

}
